package com.youthfilmic.yuejian.controller;

import com.youthfilmic.yuejian.dao.ApplicationDao;
import com.youthfilmic.yuejian.dao.TextInfoDao;
import com.youthfilmic.yuejian.domain.Application;
import com.youthfilmic.yuejian.domain.TextInfo;
import com.youthfilmic.yuejian.service.MobileServiceImpl;
import com.youthfilmic.yuejian.util.XMLUtil;
import com.youthfilmic.yuejian.weixin.pay.WeixinPayAPI;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

/**
 * Created by youweixi on 15/10/10.
 */
@Controller
@RequestMapping("/main/pay")
public class PayController {
    @Resource
    private ApplicationDao applicationDao;
    @Resource
    private TextInfoDao textInfoDao;

    @RequestMapping("/pay")
    public String payForApplication(
            @RequestParam("applicationId") Long applicationId,
            Model model
    ){
        Application application = applicationDao.findOne(applicationId);
        if (application.getStatus() == Application.STATUS_WAIT_FOR_PAID){
            model.addAttribute("application",application);
            return "main/pay/pay";
        }else{
            //订单已支付
        }
        return "redirect:/main/user/application/mine";
    }

    /**
     *
     * @title 支付回调地址(保存支付流水)
     * @url /weixin/pay/notify
     * @instructionurl https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7
     * @time 2015.7.19
     * */
    /**
     * <xml><appid><![CDATA[wxbe7b69f6478c40db]]></appid>
     * <bank_type><![CDATA[CFT]]></bank_type>
     * <cash_fee><![CDATA[1]]></cash_fee>
     * <fee_type><![CDATA[CNY]]></fee_type>
     * <is_subscribe><![CDATA[Y]]></is_subscribe>
     * <mch_id><![CDATA[1251775201]]></mch_id>
     * <nonce_str><![CDATA[55d319f10cf210c332525a5f]]></nonce_str>
     * <openid><![CDATA[o-S6RtyRzuR51I0itCFqlEIXQ5FE]]></openid>
     * <out_trade_no><![CDATA[55d319f10cf210c332525a5e]]></out_trade_no>
     * <result_code><![CDATA[SUCCESS]]></result_code>
     * <return_code><![CDATA[SUCCESS]]></return_code>
     * <sign><![CDATA[3C4CAFFC87D5CB90B772831106BF9F8F]]></sign>
     * <time_end><![CDATA[20150818194146]]></time_end>
     * <total_fee>1</total_fee>
     * <trade_type><![CDATA[JSAPI]]></trade_type>
     * <transaction_id><![CDATA[1001480423201508180650487545]]></transaction_id></xml>
     * */
    @RequestMapping("/notify.do")
    public void notifity(HttpServletRequest request , HttpServletResponse response){
        //BufferedReader br = null;
        try {
            /*br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while((line = br.readLine())!=null){
                sb.append(line);
            }*/
            BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while((line = br.readLine())!=null){
                sb.append(line);
            }
            //保存获取到的结果
            String text = sb.toString();
            TextInfo info = new TextInfo();
            info.setText(text);
            textInfoDao.save(info);

            //保证通信成功
            if(WeixinPayAPI.verifyXML(sb.toString())) {
                //验证时微信官方的消息
                JSONObject json = XMLUtil.getJsonFromXml(sb.toString());
                if (json != null && json.containsKey("return_code") && "SUCCESS".equals(json.getString("return_code"))) {
                    //微信订单号
                    Long id = json.getLong("transaction_id");
                    //只有当之前的状态是wait for pay的时候才更新状态为wait for handle
                    applicationDao.modifyStatusByIdAndStatus(id, Application.STATUS_WAIT_FOR_PAID, Application.STATUS_WAIT_FOR_HANDLE);
                    //回复微信回调完毕
                    PrintWriter w = response.getWriter();
                    w.write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
                    w.flush();
                    w.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转成功来检查一下
     * */
    @RequestMapping("/competeByQuery")
    public String competeByQuery(
            @RequestParam("applicationId") Long applicationId,
            Model model
    ){
        Application a = applicationDao.findOne(applicationId);
        if (a.getStatus() == Application.STATUS_WAIT_FOR_PAID){
            JSONObject j = WeixinPayAPI.orderQuery(applicationId);
            if (j!=null && j.containsKey("trade_state") && "SUCCESS".equals(j.getString("trade_state"))){
                //只有当之前的状态是wait for pay的时候才更新状态为wait for handle
                applicationDao.modifyStatusByIdAndStatus(applicationId, Application.STATUS_WAIT_FOR_PAID, Application.STATUS_WAIT_FOR_HANDLE);

                //短信通知电影咖
                MobileServiceImpl.SendMobileMessageForContent(a.getStar().getPhone() , MobileServiceImpl.APPLICATION_TOME);
            }
        }
        return "redirect:/main/user/application/mine";

    }

}
